package cn.zglbk.network.gateway.handler;
import cn.zglbk.config.GatewayServerConfig;
import cn.zglbk.network.gateway.GatewayMessageConsumerService;
import cn.zglbk.network.param.GameMessagePackage;
import cn.zglbk.utils.JWTUtils;
import cn.zglbk.utils.NettyUtils;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.concurrent.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author zglbk.cn
 * @email 1030681978@qq.com
 * @date 2020/10/23 19:09
 *
 */
public class DispatchGameMessageHandler extends ChannelInboundHandlerAdapter {
    /** 注入游戏网关服务配置信息。*/
    private GatewayServerConfig gatewayServerConfig;
    private JWTUtils.TokenBody tokenBody;
    private static Logger logger = LoggerFactory.getLogger(DispatchGameMessageHandler.class);

    public DispatchGameMessageHandler(GatewayServerConfig gatewayServerConfig) {
        this.gatewayServerConfig = gatewayServerConfig;
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        GameMessagePackage gameMessagePackage = (GameMessagePackage) msg;
        int serviceId = gameMessagePackage.getHeader().getServiceId();
        // 如果首次通信，获取验证信息
        if (tokenBody == null) {
            ConfirmHandler confirmHandler = (ConfirmHandler) ctx.channel().pipeline().get("ConfirmHandler");
            tokenBody = confirmHandler.getTokenBody();
        }
        String clientIp = NettyUtils.getRemoteIP(ctx.channel());
        gameMessagePackage.getHeader().setToServerId(gatewayServerConfig.getServerId());
        gameMessagePackage.getHeader().setFromServerId(gatewayServerConfig.getServerId());
        gameMessagePackage.getHeader().getAttribute().setClientIp(clientIp);
        gameMessagePackage.getHeader().setPlayerId(tokenBody.getUserId());
        gameMessagePackage.getHeader().setServiceId(serviceId);
        dispatchMessage(gameMessagePackage);
    }
    
    public static void dispatchMessage(GameMessagePackage gameMessagePackage) {
            //消息处理
        GatewayMessageConsumerService.recieve(gameMessagePackage);
    }
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
         ctx.close();
         logger.error("服务器异常，连接{}断开",ctx.channel().id().asShortText(),cause);
    }
}
